﻿/**********************************************************************/
/*                                                                    */
/*                   embDocumentInhalator                             */
/*             http://embdocumentinhalator.codeplex.com/              */
/*                                                                    */
/*               (c) Copyright 2010 Ilija Injac         .             */
/*                                                                    */
/*  This source is subject to the CDDL License                        */
/*  http://embdocumentinhalator.codeplex.com/license                  */
/*                                                                    */
/*                                                                    */
/**********************************************************************/
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WIA;
using System.IO;
using System.Security;
using System.Collections;

[assembly: AllowPartiallyTrustedCallers]
namespace embWIAScan
{
    /// <summary>
    /// Scan only one image at a time.
    /// Sample Code taken and modified from:
    /// http://www.codeguru.com/forum/showthread.php?t=439027
    /// </summary>
    public class embWIAFlatbedScan
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="embWIAFlatbedScan"/> class.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 22.01.2011,18:39
        public embWIAFlatbedScan()
        {

        }

        /// <summary>
        /// Holding the WIA-Device-ID of the Scanner
        /// </summary>
        private string DeviceID;
        /// <summary>
        /// Holds the file extension for the scanned image
        /// </summary>
        private string FileExtension;
        /// <summary>
        /// Holds the image format for the scanned extension.
        /// </summary>
        private string ImageFormat;

        

        /// <summary>
        /// Scan Image from flatbed scanner.
        /// </summary>
        /// <param name="wiaImageType">Set the image type. Use WiaConstanst.[ImageFileType]</param>
        /// <param name="filePath">Full path to save the images to. Please add trailing backslash!</param>
        /// <param name="fileName">The filename for the image. Only filename without extension.</param>
        public void ScanFlatbedImage(string wiaImageType, string filePath, string fileName,object hResolution,object vResolution)
        {


         
            //Choose Scanner
            CommonDialog class1 = new CommonDialog();
           
            //Show only available scanners in selection dialog
            Device d = class1.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);

           

            if (d != null)
            {
                this.DeviceID = d.DeviceID;
                
                
                //Set the filetype for scanning
                switch (wiaImageType)
                {
                    case WIAConstants.wiaFormatBMP:
                        FileExtension = ".bmp";
                        ImageFormat = WIAConstants.wiaFormatBMP;
                        break;
                    case WIAConstants.wiaFormatGIF:
                        FileExtension = ".gif";
                        ImageFormat = WIAConstants.wiaFormatGIF;
                        break;
                    case WIAConstants.wiaFormatJPEG:
                        FileExtension = ".jpeg";
                        ImageFormat = WIAConstants.wiaFormatJPEG;
                        break;
                    case WIAConstants.wiaFormatPNG:
                        FileExtension = ".png";
                        ImageFormat = WIAConstants.wiaFormatPNG;
                        break;
                    case WIAConstants.wiaFormatTIFF:
                        FileExtension = ".tiff";
                        ImageFormat = WIAConstants.wiaFormatTIFF;
                        break;
                    default:
                        FileExtension = ".tiff";
                        ImageFormat = WIAConstants.wiaFormatTIFF;
                        break;

                }

               
            }
            else
            {
                //no scanner chosen
                return;
            }

            //Create the WIA CommonDialog
            //Create WIA Common dialog
            WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();
           
            

            //Connect to the scanner
            //Create DeviceManager
            DeviceManager manager = new DeviceManager();
            Device WiaDev = null;
            foreach (DeviceInfo info in manager.DeviceInfos)
            {
                if (info.DeviceID == this.DeviceID)
                {
                    WIA.Properties infoprop = null;
                    
                    infoprop = info.Properties;
                    
                    //connect to scanner
                    WiaDev = info.Connect();




                    break;
                }
            }


            //Scan the image
            WIA.ImageFile img = null;
            WIA.Item Item = WiaDev.Items[1] as WIA.Item;

            foreach (WIA.Property itemProperty in Item.Properties)
            {
                //Console.WriteLine(itemProperty.Name);

                if (itemProperty.Name.Equals("Horizontal Resolution"))
                {

                    ((IProperty)itemProperty).set_Value(ref hResolution);
                }
                else if (itemProperty.Name.Equals("Vertical Resolution"))
                {


                    ((IProperty)itemProperty).set_Value(ref vResolution);
                }
            }

            try
            {

                img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, ImageFormat, false);
                

                //process image:

                string varImageFileName = filePath + fileName  + FileExtension;
                if (File.Exists(varImageFileName))
                {
                    //file exists, delete it
                    File.Delete(varImageFileName);
                }
                img.SaveFile(varImageFileName);
                
                img = null;

            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error: " + ex.Message);
                //No Pages left
               
            }



        }
        
        /// <summary>
        /// Scans the image and returns the image as byte array.
        /// </summary>
        /// <param name="wiaImageType">Type of the wia image.</param>
        /// <param name="filePath">The file path.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="hResolution">The h resolution.</param>
        /// <param name="vResolution">The v resolution.</param>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 29.01.2011,20:33
        public  byte[] ScanFlatbedImageBytes(string wiaImageType, string filePath, string fileName, object hResolution, object vResolution)
        {


           // ArrayList devs = EnumerateDevices();
            //Choose Scanner
            CommonDialog class1 = new CommonDialog();

            //Show only available scanners in selection dialog
            
            Device d = class1.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);

            //DeviceManager manager = new DeviceManager();


            if (d != null)
            {
                this.DeviceID = d.DeviceID;


                //Set the filetype for scanning
                switch (wiaImageType)
                {
                    case WIAConstants.wiaFormatBMP:
                        FileExtension = ".bmp";
                        ImageFormat = WIAConstants.wiaFormatBMP;
                        break;
                    case WIAConstants.wiaFormatGIF:
                        FileExtension = ".gif";
                        ImageFormat = WIAConstants.wiaFormatGIF;
                        break;
                    case WIAConstants.wiaFormatJPEG:
                        FileExtension = ".jpeg";
                        ImageFormat = WIAConstants.wiaFormatJPEG;
                        break;
                    case WIAConstants.wiaFormatPNG:
                        FileExtension = ".png";
                        ImageFormat = WIAConstants.wiaFormatPNG;
                        break;
                    case WIAConstants.wiaFormatTIFF:
                        FileExtension = ".tiff";
                        ImageFormat = WIAConstants.wiaFormatTIFF;
                        break;
                    default:
                        FileExtension = ".tiff";
                        ImageFormat = WIAConstants.wiaFormatTIFF;
                        break;

                }


            }
            else
            {
                //no scanner chosen
                return new byte[]{};
            }

            //Create the WIA CommonDialog
            //Create WIA Common dialog
            WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();



            //Connect to the scanner
            //Create DeviceManager
            DeviceManager manager = new DeviceManager();
            Device WiaDev = null;
            foreach (DeviceInfo info in manager.DeviceInfos)
            {
                if (info.DeviceID == this.DeviceID)
                {
                    WIA.Properties infoprop = null;

                    infoprop = info.Properties;

                    //connect to scanner
                    WiaDev = info.Connect();




                    break;
                }
            }


            //Scan the image
            WIA.ImageFile img = null;
            WIA.Item Item = WiaDev.Items[1] as WIA.Item;

            foreach (WIA.Property itemProperty in Item.Properties)
            {
                //Console.WriteLine(itemProperty.Name);

                if (itemProperty.Name.Equals("Horizontal Resolution"))
                {

                    ((IProperty)itemProperty).set_Value(ref hResolution);
                }
                else if (itemProperty.Name.Equals("Vertical Resolution"))
                {


                    ((IProperty)itemProperty).set_Value(ref vResolution);
                }
            }

            try
            {

                img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, ImageFormat, false);
                
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error: " + ex.Message);
                //No Pages left
                throw ex;
            }

            //process image:
            return (byte[])img.FileData.get_BinaryData();

        }

        /// <summary>
        /// Scans the image for SharePoint and returns a byte array
        /// containing the image.
        /// </summary>
        /// <param name="scannerName">Name of the scanner.</param>
        /// <param name="resolution">The resolution.</param>
        /// <param name="imageFormat">The image format.</param>
        /// <param name="preferredColorFormat">The preferred color format</param>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 29.01.2011,20:34
        public byte[] ScanToSharePoint(string scannerName, object resolution, string imageFormat,string preferredColorFormat)
        {
            Device scanner = null;

            DeviceManager manager = new DeviceManager();
            foreach (DeviceInfo info in manager.DeviceInfos)
            {
                if (info.Type == WIA.WiaDeviceType.ScannerDeviceType)
                {
                    foreach (WIA.Property prop in info.Properties)
                    {
                        if (prop.Name == "Name")
                        {
                            if (scannerName == ((WIA.IProperty)prop).get_Value().ToString())
                            {
                                //Console.WriteLine(((WIA.IProperty)prop).get_Value().ToString());
                                //Console.WriteLine("Connecting to Scanner {0}", ((WIA.IProperty)prop).get_Value().ToString());
                                scanner = info.Connect();

                            }

                        }

                    }
                }
            }

            //Scan the image
            WIA.ImageFile img = null;
            WIA.Item Item = scanner.Items[1] as WIA.Item;


            foreach (WIA.Property itemProperty in Item.Properties)
            {
                //Console.WriteLine(itemProperty.Name);

                if (itemProperty.Name.Equals("Horizontal Resolution"))
                {

                    ((IProperty)itemProperty).set_Value(ref resolution);
                }
                else if (itemProperty.Name.Equals("Vertical Resolution"))
                {


                    ((IProperty)itemProperty).set_Value(ref resolution);
                }
                //else if (itemProperty.Name.Equals("Current Intent"))
                //{
                //    object o = GetColorMode(preferredColorFormat);
                //    ((IProperty)itemProperty).set_Value(ref);
                //}
        
            }

            //Please be careful here
            //TODO:Handle exption
            SetProp(Item.Properties, 6146, GetColorMode(preferredColorFormat));



            byte[] imageData;

            try
            {
                img = (ImageFile)Item.Transfer(imageFormat);

                imageData = (byte[])img.FileData.get_BinaryData();

                if (imageData != null)
                {
                    return imageData;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Gets the color mode.
        /// </summary>
        /// <param name="colorModeChoosen">The color mode choosen.</param>
        /// <returns></returns>
        public static int GetColorMode(string colorModeChoosen)
        {
            switch (colorModeChoosen)
            {
                case "text":
                  return  (int) WiaImageIntent.TextIntent;
                case "color":
                    return (int) WiaImageIntent.ColorIntent;
                case "grayscale":
                    return (int) WiaImageIntent.GrayscaleIntent;
                default:
                    return (int) WiaImageIntent.ColorIntent;
            }

        }

        /// <summary>
        /// Sets the prop.
        /// </summary>
        /// <param name="properties">The properties.</param>
        /// <param name="propId">The prop id.</param>
        /// <param name="propValue">The prop value.</param>
        private void SetProp(WIA.Properties properties, int propId, object propValue)
        {
            WIA.Property prop = FindProp(properties, propId);
            prop.set_Value(ref propValue);

        }


        /// <summary>
        /// Finds the prop.
        /// </summary>
        /// <param name="properties">The properties.</param>
        /// <param name="propId">The prop id.</param>
        /// <returns></returns>
        private Property FindProp(WIA.Properties properties, int propId)
        {
            foreach (WIA.Property p in properties)
                if (p.PropertyID == propId)
                    return p;
            return null;

        } 


    }
}
